<?php

namespace Portal\Api;

use PhalApi\Request\Formatter\IntFormatter;
use Portal\Common\Api as Api;

/**
 * 文件接口
 */

class Upload extends Api
{
    public function getRules()
    {
        return array(
            'go' => array(
                'file' => array(
                    'name' => 'file',        // 客户端上传的文件字段
                    'type' => 'file',
                    'require' => true,
                    'max' => 2097152,        // 最大允许上传2M = 2 * 1024 * 1024,
                    'range' => array('image/jpeg', 'image/png','image/gif'),  // 允许的文件格式
                    'ext' => 'jpeg,jpg,png,gif', // 允许的文件扩展名
                    'desc' => '待上传的图片文件',
                ),
            ),
            'delete' => array(
                'filePath' => array('name' => "filePath","require" => true,'regex' => "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i",'desc' => '删除的图片地址'),
            ),

        );
    }

    /**
     * 图片文件上传
     * @desc 只能上传单个图片文件
     * @method POST
     * @version 2.3
     * @return int code 操作状态码，0成功，1失败
     * @return url string 成功上传时返回的图片URL
     */
    public function go()
    {
        $rs = array('code' => 0, 'url' => '');
        $tmpName = $this->file['tmp_name'];
        $name = date('YmdHis').rand(10000, 99999);
        $ext = strrchr($this->file['name'], '.');
        $uploadFolder = sprintf('%s/public/uploads/', API_ROOT);
        $daydir = date('Ymd').'/';
        $uploadFolder = $uploadFolder.$daydir;
        if (!is_dir($uploadFolder)) {
            mkdir($uploadFolder, 0777);
        }
        $hostname = isset($_ENV['HOST']) ? $_ENV['HOST'] : $_SERVER['HTTP_HOST'];
        $hostname = 'http://'.$hostname;
        $imgPath = $uploadFolder .  $name . $ext;
        if (move_uploaded_file($tmpName, $imgPath)) {
            $rs['code'] = 1;
            $rs['url'] = sprintf('%s/uploads/%s%s%s', $hostname, $daydir, $name, $ext);
            $rs['name'] = $name;
        }
        return $rs;
    }
    /**
    * 根据图片URL删除图片
    * @desc  根据图片URL删除图片
    * @method DELETE
    */
    public function delete()
    {
        $filePath = $this->filePath;
        $filePath = $this->urlToLocalPath($filePath);
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        return [];
    }


    private function urlToLocalPath($imageUrl)
    {
        // 解析URL获取路径部分
        $parsedUrl = parse_url($imageUrl);
        $path = $parsedUrl['path'] ?? '';

        // 移除开头的斜杠
        $path = ltrim($path, '/');

        // 创建完整本地路径
        $localPath = API_ROOT .'/public/'. $path;

        // 确保目录存在
        $dir = dirname($localPath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        return $localPath;
    }

}
